package com.burningtower.service.impl;

import com.burningtower.entity.Cart;
import com.burningtower.entity.OrderItem;
import com.burningtower.entity.Product;
import com.burningtower.repo.OrderItemRepository;
import com.burningtower.service.CartService;
import com.burningtower.service.OrderItemService;
import com.burningtower.service.ProductService;
import com.burningtower.vo.OrderItemVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Service
public class OrderItemServiceImpl implements OrderItemService {
    @Autowired
    private OrderItemRepository repository;
    @Autowired
    private CartService cartService;
    @Autowired
    private ProductService productService;

    @Override
    public OrderItem add(OrderItem orderItem) {
        return repository.save(orderItem);
    }

    @Override
    public List<OrderItem> getListByOrderNo(Long orderNo) {
        OrderItem item=new OrderItem();
        item.setOrderNo(orderNo);
        return repository.findAll(Example.of(item));
    }

    @Override
    public List<OrderItemVo> toVoList(List<OrderItem> itemList) {
        List<OrderItemVo> itemVoList=new ArrayList<>();
        for(OrderItem item:itemList){//将所有orderItem赋值给orderItemVo
            OrderItemVo itemVo=new OrderItemVo();
            BeanUtils.copyProperties(item,itemVo);
            itemVo.setProductImage(item.getProductImage());

            String productImage = itemVo.getProductImage();
            productImage="http://img.happymmall.com/"+productImage;
            itemVo.setProductImage(productImage);
            itemVoList.add(itemVo);
        }
        return itemVoList;
    }

    @Override
    public List<OrderItemVo> getVoListByUserId(@NotNull Integer userId) {
        List<Cart> cartList = cartService.getListByUserId(userId);
        List<OrderItemVo> itemVoList=new ArrayList<>();
        for(Cart cart:cartList){//遍历购物车中每条商品
            Product product = productService.get(cart.getProductId());//联查得到对应商品
            OrderItemVo itemVo=new OrderItemVo();
            //获取单条总价（单价*数量）
            BigDecimal price = product.getPrice().multiply(new BigDecimal(cart.getQuantity()));
            itemVo.setCurrentUnitPrice(product.getPrice());
            itemVo.setProductId(cart.getProductId());
            itemVo.setProductName(product.getName());
            itemVo.setProductImage(product.getMainImage());
            itemVo.setQuantity(cart.getQuantity());
            itemVo.setTotalPrice(price);
            itemVoList.add(itemVo);
        }
        return itemVoList;
    }
}
